<template>
  <div class="app-container">

    <div class="top-bar-container">
      <el-row>
        <el-col :span="24">
          <el-row type="flex" justify="end">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="createSubCategory(0,'顶级栏目')">新增栏目</el-button>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="list"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      fit
      stripe
      highlight-current-ro
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="栏目名称" min-width="360" />
      <el-table-column prop="code" label="栏目编码" min-width="360" />
      <el-table-column prop="type" label="栏目类型" :formatter="formatterType" />
      <el-table-column prop="indexShow" label="是否首页显示" :formatter="formatterYesOrNo" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column align="center" label="更新时间">
        <template slot-scope="{row}">
          <span>{{ row.updatedTime | formatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="280">
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="createSubCategory(scope.row.id,scope.row.name)">添加下级</el-button>
            <el-button type="warning" size="mini" icon="el-icon-edit" @click="editCategory(scope.row.id,scope.row.name)">编辑</el-button>
            <el-button v-if="scope.$index>0" type="danger" size="mini" icon="el-icon-delete" @click="deleteOffice(scope.row.id)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="editForm.id ? '编辑栏目' : '添加下级栏目'"
      :visible.sync="dialogEditVisible"
      width="500px"
      @close="handleEditFormDialogClose"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" class="edit-form" autocomplete="on" label-position="right" label-width="100px">
        <el-form-item prop="parentId" label="父级栏目">
          <el-input
            v-model="editForm.parentName"
            placeholder="请选择栏目"
            class="width-220 selectTree-input"
            auto-complete="off"
            @click.native="changeSelectTree()"
            @blur="hideParentClick"
          />
          <el-tree
            v-show="isShowSelect"
            id="floatTree"
            ref="selectTree"
            empty-text="暂无数据"
            :highlight-current="true"
            :default-expand-all="true"
            :expand-on-click-node="true"
            :data="list"
            :filter-node-method="filterNode"
            class="width-220 selectTree-input objectTree"
            @node-click="selectClassfy"
          />
        </el-form-item>
        <el-form-item prop="name" label="栏目名称">
          <el-input v-model="editForm.name" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item prop="code" label="栏目编码">
          <el-input v-model="editForm.code" placeholder="请输入栏目编码" />
        </el-form-item>
        <el-form-item prop="type" label="栏目类型">
          <el-select v-model="editForm.type" placeholder="请选择">
            <el-option
              v-for="item in categoryType"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="indexShow" label="是否首页显示">
          <el-select v-model="editForm.indexShow" placeholder="请选择">
            <el-option
              v-for="item in yesNoStatusList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="linkedUrl" label="链接">
          <el-input v-model="editForm.linkedUrl" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item prop="sort" label="同级排序">
          <el-input-number v-model="editForm.sort" :min="0" :max="1000" :step="1" label="排序值" />（数值大靠前）
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { categoryList, categoryTypes, createCategory, getCategory, deleteCategory, editCategory } from '@/api/rest/cms/category'
import { elRequiredRule, elValidateInteger } from '@/utils/el-validator'
import { yesNoStatusList } from '@/utils/dict'
import { formatDateTime } from '@/utils/formatdate'
const initForm = {
  id: null,
  name: null,
  code: null,
  linkedUrl: '',
  indexShow: 0,
  sort: 0,
  parentId: null,
  parentName: '',
  type: 0
}

export default {
  name: 'CategoryList',
  filters: {
    formatTime(val) {
      if (val) {
        return formatDateTime(val)
      }
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      loading: false,
      dialogEditVisible: false,
      parentName: '',
      editForm: { ...initForm },
      editRules: {
        name: elRequiredRule,
        code: elRequiredRule,
        parentId: elRequiredRule,
        sort: [{ trigger: 'change', validator: elValidateInteger }],
        type: elRequiredRule
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      categoryType: [
      ],
      yesNoStatusList: yesNoStatusList,
      isShowSelect: false
    }
  },
  watch: {
    // $route(to, from) {
    //   this.getCategoryList()
    // }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    getCategoryList() {
      this.listLoading = true
      categoryList(this.listQuery).then(response => {
        this.list = response.data
      })
      categoryTypes().then(response => {
        this.categoryType = response.data
      })
    },
    createSubCategory(parentId, parentName) {
      this.editForm = { ...initForm }
      this.editForm.parentId = parentId
      this.editForm.parentName = parentName
      this.dialogEditVisible = true
    },
    deleteOffice(id) {
      this.$confirm('此操作将删除栏目, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteCategory(id).then(response => {
          if (response.code === 0) {
            this.$message({
              message: '删除栏目成功',
              type: 'success'
            })
            this.getCategoryList()
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            })
          }
        }).catch(() => {})
      })
    },
    editCategory(id) {
      const that = this
      getCategory(id).then(response => {
        if (response.code === 0) {
          that.editForm = response.data
        }
      })
      this.dialogEditVisible = true
    },
    saveCategory() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.editForm.id) {
            editCategory(this.editForm).then(response => {
              if (response.code === 0) {
                this.$message({
                  message: '编辑栏目成功',
                  type: 'success'
                })
                this.getCategoryList()
                this.dialogEditVisible = false
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                })
              }
            })
          } else {
            createCategory(this.editForm).then(response => {
              if (response.code === 0) {
                this.$message({
                  message: '添加栏目成功',
                  type: 'success'
                })
                this.getCategoryList()
                this.dialogEditVisible = false
              } else {
                this.$message({
                  message: response.message,
                  type: 'error'
                })
              }
            })
          }
        }
      })
    },
    formatterType(row) {
      const type = this.categoryType.find(f => f.value === row.type)
      return type ? type.name : ''
    },
    formatterYesOrNo(row) {
      const type = this.yesNoStatusList.find(f => f.value === row.indexShow)
      return type ? type.name : ''
    },
    handleEditFormDialogClose() {
      this.$refs.editForm.clearValidate()
    },
    selectClassfy(data) {
      this.editForm.parentName = data.label
      this.editForm.parentId = data.id
      this.isShowSelect = false
    },
    changeSelectTree() {
      if (!this.editForm.id || this.editForm.parentId !== 0) {
        this.isShowSelect = true
      }
    },
    hideParentClick(e) {
      const isOther = e.relatedTarget == null || e.relatedTarget.closest('div.el-tree') == null || e.relatedTarget.closest('div.el-tree').id !== 'floatTree'

      if (isOther) {
        this.isShowSelect = false
      } else {
        e.target.focus()
      }
    },
    // 选择器的树节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>
<style>
  /*下拉框选择树*/
  .objectTree {
    margin-left:0px;
    position: absolute;
    overflow: auto;
    z-index: 100;
    height: 200px;
    border: 1px solid #ddd;
    line-height: normal;
    z-index: 204;
  }
  .width-220{
    width: 220px
  }
</style>

